package com.ruoyi.utils.wwx;

import com.ruoyi.wwxkf.domain.WxMsgRevice;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;

@Slf4j
public class WwxMsgUtil {

    /**
     * 字符串进行解析
     * @return
     */
    public static WxMsgRevice DecryptMsgParse(String xmlString){
        WxMsgRevice message = new WxMsgRevice();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            ByteArrayInputStream input = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
            Document doc = builder.parse(input);

            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getDocumentElement().getChildNodes();

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    switch (element.getNodeName()) {
                        case "ToUserName":
                            message.setToUserName(element.getTextContent());
                            break;
                        case "CreateTime":
                            message.setCreateTime(Long.parseLong(element.getTextContent()));
                            break;
                        case "MsgType":
                            message.setMsgType(element.getTextContent());
                            break;
                        case "Event":
                            message.setEvent(element.getTextContent());
                            break;
                        case "Token":
                            message.setToken(element.getTextContent());
                            break;
                        case "OpenKfId":
                            message.setOpenKfId(element.getTextContent());
                            break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("接受微信用户消息解析失败：{}", e.getMessage());
        }
        return message;
    }

    public static void main(String[] args) {
        String s =" <xml><ToUserName><![CDATA[ww381c803ff4e460b9]]></ToUserName><CreateTime>1741101240</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[kf_msg_or_event]]></Event><Token><![CDATA[ENCHTAx68cemrJZfaPPHQX9u4sX9C7buzjxVyhHTmZ9ZZAs]]></Token><OpenKfId><![CDATA[wkIFfwXQAAkHdiVwo1wr_d5dzQZk9Lxg]]></OpenKfId></xml>";
        System.out.println(DecryptMsgParse(s));
    }

}
